﻿using AccustomeAttributedll;
using AixCommInfo;
using ISaveReaddll;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FinalTestMachine.Motion.Aixs;
using FinalTestMachine.Motion.IO;
using System.Threading;
using FinalTestMachine.Motion.Aixs.Site6;
using AM.Core.IO;

namespace FinalTestMachine.Motion.Aixs
{
    /// <summary>
    /// 旋转轴
    /// </summary>
    public class Aix_Turn : AixCreateBase
    {
        private Aix_Turn() : base(AM.Core.Axis.AxisInfoManger.GetAxisInfo(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name))
        {
        }

        public static readonly Aix_Turn Cur = new Aix_Turn();

        public static Aix_Turn CreateInstrance()
        {
            return Cur;
        }


        #region 手动修改数据
        /// <summary>
        /// 转到下一工位所需要的角度
        /// </summary>
        public const double PerRad = 360 / StationNum;

        public const int StationNum = GlobalParams.WorkstationSum;

        #endregion

        #region 覆写方法区
        public override void Mov(double dis)
        {
            base.Mov(dis);
        }
        public override void JOGP()
        {
            SafeCheck();
            base.JOGP();
        }

        public override void JOGN()
        {
            SafeCheck();
            base.JOGN();
        }

        public override void SafeCheck()
        {
            //保证转盘在转动时不会与测试部件发生任何干涉
            //光筒轴到达等待位

            void CheckAixSafePos(AixCreateBase axis)
            {
                if (axis.CheckSafePos())
                {
                    return;
                }
                else
                {
                    throw new Exception($"主轴启动失败：{axis.Name}不在等待位！");
                }
            }

            void CheckCylinderSafePos(Cylinder cylinder)
            {
                if (!cylinder.GetOriginPosState())
                {
                    throw new Exception($"主轴启动失败：{cylinder.CylinderName}不在上升位，可能影响主轴运动！");
                }
            }

            CheckAixSafePos(Aix_Site6_PipeUpDown.Cur);
            CheckAixSafePos(Aixs.Site2.Aix_Site2_PlaneSourceLift.Cur);
            CheckAixSafePos(Aixs.Site2.Aix_Site2_RelayMirror.Cur);
            CheckAixSafePos(Aixs.Site4.Aix_Site4_PlaneSourceLift.Cur);
            CheckAixSafePos(Aixs.Site4.Aix_Site4_RelayMirror.Cur);

            CheckCylinderSafePos(StaticIOHelper.Cylinder_SiteBowlLightUpDown);
            CheckCylinderSafePos(StaticIOHelper.Cylinder_Site4LeftLightUpDown);
            CheckCylinderSafePos(StaticIOHelper.Cylinder_Site4RightLightUpDown);
            CheckCylinderSafePos(StaticIOHelper.Cylinder_Site5Lift);


            //安全光栅判断
            if (Funs.FunCommSelection.Cur.IsUseSafetyGrating)
            {
                if (!StaticIOHelper.In_Safe_Checked.In())
                {
                    throw new Exception("主轴启动失败：光栅检测异常！");
                }
            }

            #region 治具开合检测
            if (!StaticIOHelper.Fun_CheckSocketAIsOpen())
            {
                throw new Exception("主轴启动失败：载具A开合检测异常！");
            }

            if (!StaticIOHelper.Fun_CheckSocketBIsOpen())
            {
                throw new Exception("主轴启动失败：载具B开合检测异常！");
            }

            if (!StaticIOHelper.Fun_CheckSocketCIsOpen())
            {
                throw new Exception("主轴启动失败：载具C开合检测异常！");
            }

            if (!StaticIOHelper.Fun_CheckSocketDIsOpen())
            {
                throw new Exception("主轴启动失败：载具D开合检测异常！");
            }

            if (!StaticIOHelper.Fun_CheckSocketEIsOpen())
            {
                throw new Exception("主轴启动失败：载具E开合检测异常！");
            }

            if (!StaticIOHelper.Fun_CheckSocketFIsOpen())
            {
                throw new Exception("主轴启动失败：载具F开合检测异常！");
            }
            #endregion
        }

        [ButtonRemark("回原点", EnumColor.LightGreen)]
        public override void Home()
        {
            SafeCheck();
            RotatedMovNextHelper.Reset();
            //base.Home();
            WaitPos.Mov();
            IsHomeOK = true;
        }

        #endregion 覆写方法区

        #region 功能实例
        [SaveRemark]
        [TextBoxRemark("等待位")]
        public SingleAixPosAndSpeedMsgAndIMov WaitPos = new SingleAixPosAndSpeedMsgAndIMov(() => Cur);

        #endregion 功能实例

        #region 方法操作

        [ButtonRemark("等待位")]
        public bool Mov_0()
        {
            return Mov_xPos(0);
        }

        

        /// <summary>
        /// 所有针对转盘的移动命令都要经由此方法，是为确保下一计数不出问题
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public bool Mov_xPos(int index)
        {
            SafeCheck();
            bool isrecord = true;
            Task.Run(() => {
                while (isrecord)
                {
                    if (this.GetCmdPos() > this.GetEncPos() + 15)
                    {
                        this.StopSlowDown();
                        throw new Exception("当前转盘电机反馈脉冲和输出脉冲相差大于15");
                    }
                    Thread.Sleep(200);
                }
            });

            //对旋转轴进行移动
            MovAbs(PerRad * index + WaitPos.PosMsg.GetValue);

            isrecord = false;
            if (this.CheckPos(WaitPos.PosMsg.GetValue + PerRad * index, 2))
            {
                MovAbs(PerRad * index + WaitPos.PosMsg.GetValue);
                //设置下一个要转的位置索引
                RotatedMovNextHelper.SetIndex((index + 1) >= StationNum ? 0 : (index + 1));
                return true;
            }
            else
            {
                return false;
            }
        }

        [ButtonRemark("下一工位")]
        public void MovNext()
        {
            RotatedMovNextHelper.MovNext();
        }

        #endregion 方法操作
    }

    public enum RotateDir
    {
        ClockWise,
        AntiClockWise
    }
}